package cn.amaake.magicplugin.nacos.service;

import org.apache.dubbo.rpc.service.GenericException;
import org.apache.dubbo.rpc.service.GenericService;
import org.ssssssss.magicapi.core.exception.MagicAPIException;
import org.ssssssss.magicapi.core.model.Parameter;
import org.ssssssss.magicapi.core.service.MagicAPIService;
import org.ssssssss.magicapi.function.model.FunctionInfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MagicApiGenericService implements GenericService {

    private String serviceName;
    private MagicAPIService magicAPIService;
    private List<FunctionInfo> functionlists;

    public MagicApiGenericService(String serviceName, MagicAPIService magicAPIService,List<FunctionInfo> functionlists) {
        this.serviceName = serviceName;
        this.magicAPIService = magicAPIService;
        this.functionlists = functionlists;
    }

    @Override
    public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException {
        FunctionInfo functionInfo = functionlists.stream()
                .filter(functionInfo1 -> functionInfo1.getPath().replace("/","").equals(method))
                .findFirst()
                .orElse(null);

//
//        for(FunctionInfo b : functionlists){
//            String functionid = b.getId();
//            String functionname = b.getName();
//            String functionpath = b.getPath();
//            for(Parameter parameter : b.getParameters()){
//                String parametername = parameter.getName();
//                String type = parameter.getType();
//
//            }
//        }

        List<Parameter> parameters = functionInfo.getParameters();
        if(parameters.size() != args.length){
            throw new MagicAPIException("参数位数不一致！");
        }
        Map<String, Object> params = new HashMap<>();
        // 注入变量信息
        for(int i = 0;i < parameters.size();i++){
            params.put(parameters.get(i).getName(), args[i]);
        }

        // 调用函数
        Object value = magicAPIService.invoke("/"+serviceName+"/"+method+"", params);
        return value;
    }
}
